<template>
  <div class="scenic-detail-page">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <!-- 面包屑导航 -->
      <div
        class="container mx-auto px-4 py-4 border-b border-gray-200 dark:border-gray-700"
      >
        <Breadcrumb
          :items="[
            { path: '/', title: '首页' },
            { path: '/scenic', title: '景区门票' },
            { title: scenic.name || '景区详情' },
          ]"
        />
      </div>

      <div class="container mx-auto px-4 py-6">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
              {{ scenic.name }}
            </h1>
            <p class="text-gray-600 dark:text-gray-400 mt-2">
              {{ scenic.description }}
            </p>
          </div>
          <div class="flex items-center gap-3">
            <el-button-group>
              <el-button type="primary" plain :icon="Share" @click="handleShare"
                >分享</el-button
              >
              <el-button
                :type="scenic.isFavorite ? 'primary' : 'default'"
                plain
                :icon="Star"
                @click="handleToggleFavorite"
              >
                {{ scenic.isFavorite ? "已收藏" : "收藏" }}
              </el-button>
            </el-button-group>
          </div>
        </div>
      </div>
    </div>

    <!-- 景点基本信息 -->
    <div class="scenic-header bg-white border-b border-gray-200">
      <div class="container mx-auto px-4 py-8">
        <div class="flex flex-col lg:flex-row gap-8">
          <!-- 左侧图片轮播 -->
          <div class="lg:w-1/2">
            <Carousel
              :images="scenic.images"
              :autoplay="true"
              class="aspect-[4/3] rounded-lg overflow-hidden"
            />
          </div>

          <!-- 右侧信息 -->
          <div class="lg:w-1/2">
            <div class="flex items-center justify-between mb-4">
              <h1 class="text-2xl font-bold text-gray-900">
                {{ scenic.name }}
              </h1>
              <el-button
                circle
                :type="scenic.isFavorite ? 'danger' : 'default'"
                @click="handleToggleFavorite"
              >
                <el-icon>
                  <Star :filled="scenic.isFavorite" />
                </el-icon>
              </el-button>
            </div>

            <!-- 评分和标签 -->
            <div class="meta-info mb-6">
              <div class="rating flex items-center mb-3">
                <el-rate
                  v-model="scenic.rating"
                  disabled
                  :max="5"
                  allow-half
                  class="mr-2"
                />
                <span class="text-orange-500 text-lg font-medium mr-2">
                  {{ scenic.rating }}
                </span>
                <span class="text-gray-500">
                  {{ scenic.reviewCount }}条评价
                </span>
              </div>
              <div class="tags flex flex-wrap gap-2">
                <el-tag v-for="tag in scenic.tags" :key="tag" size="default">
                  {{ tag }}
                </el-tag>
              </div>
            </div>

            <!-- 基本信息 -->
            <div class="info-list space-y-4 mb-6">
              <div class="info-item flex items-start">
                <el-icon class="text-gray-400 mt-1 mr-2"><Location /></el-icon>
                <div class="flex-1">
                  <div class="text-gray-900">{{ scenic.address }}</div>
                  <el-button type="primary" link @click="handleViewMap">
                    查看地图
                  </el-button>
                </div>
              </div>
              <div class="info-item flex items-start">
                <el-icon class="text-gray-400 mt-1 mr-2"><Clock /></el-icon>
                <div class="flex-1">
                  <div class="text-gray-900">{{ scenic.openTime }}</div>
                  <div class="text-gray-500 text-sm">
                    {{ scenic.openTimeNote }}
                  </div>
                </div>
              </div>
              <div class="info-item flex items-start">
                <el-icon class="text-gray-400 mt-1 mr-2"><Phone /></el-icon>
                <div class="flex-1">
                  <div class="text-gray-900">{{ scenic.phone }}</div>
                </div>
              </div>
            </div>

            <!-- 门票信息 -->
            <div class="ticket-info bg-primary-50 rounded-lg p-6 mb-6">
              <div class="flex items-center justify-between mb-4">
                <div>
                  <div class="text-gray-500 text-sm">门票价格</div>
                  <div class="text-2xl text-primary-600 font-medium">
                    ¥{{ scenic.price }}
                    <span class="text-sm text-gray-500">起</span>
                  </div>
                </div>
                <el-button
                  type="primary"
                  size="large"
                  @click="showTicketDialog = true"
                >
                  立即预订
                </el-button>
              </div>
              <div class="text-gray-500 text-sm">
                {{ scenic.ticketNote }}
              </div>
            </div>

            <!-- 景点介绍 -->
            <div class="description text-gray-600 text-sm leading-relaxed">
              {{ scenic.description }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="flex flex-col lg:flex-row gap-8">
        <!-- 左侧主要内容 -->
        <div class="flex-1">
          <!-- 导航标签 -->
          <el-tabs v-model="activeTab" class="scenic-tabs">
            <el-tab-pane label="景点详情" name="detail">
              <!-- 景点详情 -->
              <div class="scenic-detail bg-white rounded-lg p-6">
                <h2 class="text-xl font-bold mb-6">景点介绍</h2>
                <div class="content space-y-6">
                  <div
                    v-for="(section, index) in scenic.details"
                    :key="index"
                    class="section"
                  >
                    <h3 class="text-lg font-medium mb-4">
                      {{ section.title }}
                    </h3>
                    <div class="text-gray-600 leading-relaxed mb-4">
                      {{ section.content }}
                    </div>
                    <div
                      v-if="section.images?.length"
                      class="grid grid-cols-2 gap-4"
                    >
                      <el-image
                        v-for="(image, imageIndex) in section.images"
                        :key="imageIndex"
                        :src="image"
                        :preview-src-list="section.images"
                        class="w-full rounded-lg"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="交通指南" name="traffic">
              <!-- 交通指南 -->
              <div class="traffic-guide bg-white rounded-lg p-6">
                <h2 class="text-xl font-bold mb-6">交通指南</h2>
                <div class="content space-y-6">
                  <div
                    v-for="(guide, index) in scenic.trafficGuides"
                    :key="index"
                    class="guide-item"
                  >
                    <h3 class="text-lg font-medium mb-4">
                      <el-icon class="mr-2">
                        <component :is="guide.icon" />
                      </el-icon>
                      {{ guide.title }}
                    </h3>
                    <div class="text-gray-600 leading-relaxed">
                      {{ guide.content }}
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="游客评价" name="reviews">
              <!-- 游客评价 -->
              <div class="reviews bg-white rounded-lg p-6">
                <!-- 评分统计 -->
                <div class="rating-stats flex items-center gap-8 mb-8">
                  <div class="overall-rating text-center">
                    <div class="text-3xl text-orange-500 font-bold mb-2">
                      {{ scenic.rating }}
                    </div>
                    <el-rate
                      v-model="scenic.rating"
                      disabled
                      :max="5"
                      allow-half
                      class="mb-2"
                    />
                    <div class="text-gray-500 text-sm">
                      {{ scenic.reviewCount }}条评价
                    </div>
                  </div>
                  <div class="rating-bars flex-1 space-y-2">
                    <div
                      v-for="(stat, index) in scenic.ratingStats"
                      :key="index"
                      class="rating-bar flex items-center"
                    >
                      <div class="label w-16 text-sm text-gray-500">
                        {{ stat.label }}
                      </div>
                      <div class="bar flex-1 h-2 bg-gray-100 rounded-full">
                        <div
                          class="h-full bg-orange-500 rounded-full"
                          :style="{ width: `${stat.percentage}%` }"
                        />
                      </div>
                      <div class="count w-16 text-right text-sm text-gray-500">
                        {{ stat.count }}
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 评价列表 -->
                <div class="review-list space-y-6">
                  <div
                    v-for="review in scenic.reviews"
                    :key="review.id"
                    class="review-item"
                  >
                    <div
                      class="review-header flex items-center justify-between mb-3"
                    >
                      <div class="user-info flex items-center">
                        <el-avatar :size="40" :src="review.userAvatar" />
                        <div class="ml-3">
                          <div class="font-medium">{{ review.userName }}</div>
                          <div class="text-gray-500 text-sm">
                            {{ review.createTime }}
                          </div>
                        </div>
                      </div>
                      <el-rate
                        v-model="review.rating"
                        disabled
                        :max="5"
                        allow-half
                      />
                    </div>
                    <div class="review-content text-gray-600 mb-4">
                      {{ review.content }}
                    </div>
                    <div
                      v-if="review.images?.length"
                      class="review-images grid grid-cols-4 gap-2"
                    >
                      <el-image
                        v-for="(image, index) in review.images"
                        :key="index"
                        :src="image"
                        :preview-src-list="review.images"
                        class="w-full aspect-square rounded object-cover"
                      />
                    </div>
                    <div
                      v-if="review.reply"
                      class="review-reply bg-gray-50 p-4 rounded mt-4"
                    >
                      <div class="text-primary-600 font-medium mb-2">
                        商家回复：
                      </div>
                      <div class="text-gray-600">{{ review.reply }}</div>
                    </div>
                  </div>
                </div>

                <!-- 分页 -->
                <div class="pagination flex justify-center mt-8">
                  <el-pagination
                    v-model:current-page="reviewPage"
                    v-model:page-size="reviewPageSize"
                    :total="reviewTotal"
                    :page-sizes="[10, 20, 30, 40]"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleReviewSizeChange"
                    @current-change="handleReviewPageChange"
                  />
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 右侧推荐 -->
        <div class="lg:w-80">
          <!-- 相关景点推荐 -->
          <div class="related-scenic bg-white rounded-lg p-6 mb-6">
            <h3 class="text-lg font-bold mb-4">相关景点</h3>
            <div class="space-y-4">
              <div
                v-for="item in scenic.relatedScenic"
                :key="item.id"
                class="scenic-item flex items-center cursor-pointer hover:bg-gray-50 rounded p-2"
                @click="handleViewScenic(item)"
              >
                <el-image
                  :src="item.coverImage"
                  :alt="item.name"
                  class="w-20 h-20 rounded object-cover"
                />
                <div class="ml-3 flex-1 min-w-0">
                  <div class="font-medium truncate mb-1">{{ item.name }}</div>
                  <div class="text-sm text-gray-500 mb-1">
                    {{ item.address }}
                  </div>
                  <div class="text-primary-600">¥{{ item.price }}起</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 周边美食推荐 -->
          <div class="related-food bg-white rounded-lg p-6">
            <h3 class="text-lg font-bold mb-4">周边美食</h3>
            <div class="space-y-4">
              <div
                v-for="item in scenic.relatedFood"
                :key="item.id"
                class="food-item flex items-center cursor-pointer hover:bg-gray-50 rounded p-2"
                @click="handleViewFood(item)"
              >
                <el-image
                  :src="item.coverImage"
                  :alt="item.name"
                  class="w-20 h-20 rounded object-cover"
                />
                <div class="ml-3 flex-1 min-w-0">
                  <div class="font-medium truncate mb-1">{{ item.name }}</div>
                  <div class="text-sm text-gray-500 mb-1">
                    {{ item.address }}
                  </div>
                  <div class="text-orange-500">¥{{ item.avgPrice }}/人</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 地图弹窗 -->
    <el-dialog
      v-model="showMapDialog"
      title="景点地图"
      width="80%"
      destroy-on-close
    >
      <MapView
        :center="scenic.location"
        :zoom="15"
        :markers="[
          {
            position: scenic.location,
            title: scenic.name,
            content: scenic.address,
          },
        ]"
        class="h-[600px]"
      />
    </el-dialog>

    <!-- 门票预订弹窗 -->
    <el-dialog
      v-model="showTicketDialog"
      title="门票预订"
      width="640px"
      destroy-on-close
    >
      <div class="ticket-booking space-y-6">
        <!-- 日期选择 -->
        <div class="date-select">
          <div class="label mb-2">选择日期</div>
          <DatePicker
            v-model="bookingDate"
            type="date"
            :disabled-date="disabledDate"
            placeholder="请选择游玩日期"
          />
        </div>

        <!-- 门票列表 -->
        <div class="ticket-list space-y-4">
          <div
            v-for="ticket in scenic.tickets"
            :key="ticket.id"
            class="ticket-item bg-gray-50 rounded-lg p-4"
          >
            <div class="flex items-center justify-between mb-2">
              <div class="ticket-name font-medium">{{ ticket.name }}</div>
              <div class="ticket-price text-primary-600 text-lg font-medium">
                ¥{{ ticket.price }}
              </div>
            </div>
            <div class="ticket-desc text-gray-500 text-sm mb-3">
              {{ ticket.description }}
            </div>
            <div class="flex items-center justify-between">
              <div class="text-orange-500 text-sm">
                剩余 {{ ticket.stock }} 张
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-gray-500">数量</span>
                <el-input-number
                  v-model="ticket.quantity"
                  :min="0"
                  :max="ticket.stock"
                  size="small"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 游客信息 -->
        <div class="visitor-info">
          <div class="label mb-2">游客信息</div>
          <FormInput
            v-model="visitorName"
            label="游客姓名"
            placeholder="请输入游客姓名"
            required
          />
          <FormInput
            v-model="visitorPhone"
            label="手机号码"
            placeholder="请输入手机号码"
            required
          />
        </div>
      </div>

      <template #footer>
        <div class="flex items-center justify-between">
          <div class="total-price">
            <span class="text-gray-500">总计：</span>
            <span class="text-2xl text-primary-600 font-medium">
              ¥{{ totalPrice }}
            </span>
          </div>
          <div class="space-x-2">
            <el-button @click="showTicketDialog = false">取消</el-button>
            <el-button
              type="primary"
              :disabled="!canBook"
              @click="handleBookTicket"
            >
              提交订单
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
  Location,
  Clock,
  Phone,
  Star,
  Grid,
  List,
  Share,
} from "@element-plus/icons-vue";
import Carousel from "@/components/global/Carousel.vue";
import MapView from "@/components/global/MapView.vue";
import FormInput from "@/components/global/FormInput.vue";
import DatePicker from "@/components/global/DatePicker.vue";
import Breadcrumb from "@/components/global/Breadcrumb.vue";

const route = useRoute();
const router = useRouter();

// 页面数据
const scenic = ref({
  id: 1,
  name: "贵港园博园",
  images: [
    "/images/scenic/yuanboyuan1.jpg",
    "/images/scenic/yuanboyuan2.jpg",
    "/images/scenic/yuanboyuan3.jpg",
  ],
  rating: 4.8,
  reviewCount: 1234,
  tags: ["网红打卡", "亲子游玩", "自然探索"],
  address: "贵港市港北区",
  location: [109.598556, 23.107126],
  openTime: "09:00-17:30",
  openTimeNote: "16:30停止入园（节假日延长开放时间）",
  phone: "0775-12345678",
  price: 68,
  ticketNote: "1.2米以下儿童免票，1.2-1.5米儿童半票",
  description:
    "贵港园博园是一个集园艺展示、科普教育、休闲娱乐于一体的综合性公园，园内有多个主题园区，展示了贵港特色的园林艺术和植物文化。",
  isFavorite: false,
  details: [
    {
      title: "园区介绍",
      content: "园区分为主题展园区、湿地公园区、科普教育区等多个功能区域...",
      images: [
        "/images/scenic/yuanboyuan-detail1.jpg",
        "/images/scenic/yuanboyuan-detail2.jpg",
      ],
    },
  ],
  trafficGuides: [
    {
      icon: "Bus",
      title: "公交路线",
      content: "乘坐1路、2路、3路公交车在园博园站下车即可到达。",
    },
  ],
  ratingStats: [
    { label: "5星", percentage: 85, count: 1047 },
    { label: "4星", percentage: 12, count: 148 },
    { label: "3星", percentage: 2, count: 25 },
    { label: "2星", percentage: 1, count: 12 },
    { label: "1星", percentage: 0, count: 2 },
  ],
  reviews: [
    {
      id: 1,
      userAvatar: "/images/avatars/user1.jpg",
      userName: "快乐游客",
      createTime: "2024-03-15 14:30",
      rating: 5,
      content: "园区环境优美，植物品种丰富，是一个非常适合全家出游的好去处。",
      images: [
        "/images/reviews/review1-1.jpg",
        "/images/reviews/review1-2.jpg",
      ],
      reply: "感谢您的好评，欢迎再次光临！",
    },
  ],
  tickets: [
    {
      id: 1,
      name: "成人票",
      price: 68,
      description: "适用于1.5米以上成人",
      stock: 100,
      quantity: 0,
    },
    {
      id: 2,
      name: "儿童票",
      price: 34,
      description: "适用于1.2-1.5米儿童",
      stock: 100,
      quantity: 0,
    },
  ],
  relatedScenic: [
    {
      id: 2,
      name: "贵港博物馆",
      coverImage: "/images/scenic/museum.jpg",
      address: "贵港市港北区",
      price: 0,
    },
  ],
  relatedFood: [
    {
      id: 1,
      name: "老街口小吃",
      coverImage: "/images/food/food1.jpg",
      address: "贵港市港北区老街",
      avgPrice: 30,
    },
  ],
});

// 标签页
const activeTab = ref("detail");

// 评价分页
const reviewPage = ref(1);
const reviewPageSize = ref(10);
const reviewTotal = ref(100);

// 地图弹窗
const showMapDialog = ref(false);

// 门票预订
const showTicketDialog = ref(false);
const bookingDate = ref("");
const visitorName = ref("");
const visitorPhone = ref("");

// 计算总价
const totalPrice = computed(() => {
  return scenic.value.tickets.reduce((total, ticket) => {
    return total + ticket.price * ticket.quantity;
  }, 0);
});

// 是否可以预订
const canBook = computed(() => {
  return (
    bookingDate.value &&
    visitorName.value &&
    visitorPhone.value &&
    totalPrice.value > 0
  );
});

// 禁用的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7;
};

// 处理收藏切换
const handleToggleFavorite = async () => {
  try {
    // TODO: 调用收藏/取消收藏API
    scenic.value.isFavorite = !scenic.value.isFavorite;
    ElMessage.success(scenic.value.isFavorite ? "收藏成功" : "已取消收藏");
  } catch (error) {
    ElMessage.error("操作失败，请重试");
  }
};

// 查看地图
const handleViewMap = () => {
  showMapDialog.value = true;
};

// 查看相关景点
const handleViewScenic = (item) => {
  router.push(`/scenic/${item.id}`);
};

// 查看相关美食
const handleViewFood = (item) => {
  router.push(`/food/${item.id}`);
};

// 处理评价分页
const handleReviewSizeChange = (size) => {
  reviewPageSize.value = size;
  fetchReviews();
};

const handleReviewPageChange = (page) => {
  reviewPage.value = page;
  fetchReviews();
};

// 获取评价列表
const fetchReviews = async () => {
  try {
    // TODO: 调用获取评价列表API
  } catch (error) {
    ElMessage.error("获取评价列表失败");
  }
};

// 提交订单
const handleBookTicket = async () => {
  try {
    // TODO: 调用创建订单API
    ElMessage.success("订单提交成功");
    showTicketDialog.value = false;
    router.push("/order/payment/123");
  } catch (error) {
    ElMessage.error("订单提交失败，请重试");
  }
};

// 获取景点详情
const fetchScenicDetail = async () => {
  try {
    // TODO: 调用获取景点详情API
    // const { data } = await getScenicDetail(route.params.id)
    // scenic.value = data
  } catch (error) {
    ElMessage.error("获取景点详情失败");
  }
};

onMounted(() => {
  fetchScenicDetail();
});
</script>

<style lang="scss" scoped>
.scenic-detail-page {
  .scenic-tabs {
    :deep(.el-tabs__header) {
      @apply mb-6;
    }
  }

  .rating-bars {
    .rating-bar {
      .bar {
        @apply overflow-hidden;
      }
    }
  }
}
</style>
